package com.lt.flashcard.view;

import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.metainfo.ComponentInfo;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zul.Checkbox;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import com.lt.flashcard.Utility;
import com.lt.flashcard.model.entity.Role;
import com.lt.flashcard.model.entity.User;
import com.lt.flashcard.model.service.AAService;
import com.lt.flashcard.model.service.Repository;
import com.lt.flashcard.model.service.UserService;

public class AdminUsersDetailCtrl extends SelectorComposer<Component> {

    private static final long serialVersionUID = 1L;

    private List<Role> roleList = null;
    private User user;
    String strId;

    @Override
    public ComponentInfo doBeforeCompose(Page page, Component parent, ComponentInfo compInfo) {
        AAService srv = Repository.getInstance().getAAService();
        UserService usrv = Repository.getInstance().getUserService();
        if (!srv.isLogin() || !srv.hasRole("admin")) {
            Utility.redirect("/admin_login.zul", false);
            return null;
        }
        strId = Executions.getCurrent().getParameter("id");
        try {
            long id = Long.parseLong(strId);
            if (id > 0) {
                user = usrv.findByID(id);
                roleList = usrv.getRoles();
            }
        } catch (Exception e) {
        }
        return super.doBeforeCompose(page, parent, compInfo);
    }

    @Listen("onClick=#btnDelete")
    public void doDelete() {
        Messagebox.show("Are you sure to delete this user?", "Confirm Dialog", Messagebox.OK | Messagebox.CANCEL, "0",
                new org.zkoss.zk.ui.event.EventListener<Event>() {
                    @Override
                    public void onEvent(Event event) throws Exception {
                        if (event.getName().equals("onOK")) {
                            UserService usrv = Repository.getInstance().getUserService();
                            try {
                                usrv.delete(user);
                                Executions.sendRedirect("admin_user_page.zul");
                                Messagebox.show("User had been deleted.", "Information", Messagebox.OK, Messagebox.INFORMATION);
                            } catch (Exception e) {
                                Messagebox.show(e.getMessage());
                            }
                        }
                    }
                });
    }

    @Listen("onClick=#btnEdit")
    public void doEdit() {
        HashMap<String, Object> param = new HashMap<String, Object>();
        param.put("user", user);
        Component comp = Executions.createComponents("/create_edit_user.zul", null, param);
        AdminCreateUsersCtrl ctrl = (AdminCreateUsersCtrl) comp.getAttribute("$composer");
        // Set<Role> rs = user.getRoles();
        for (Checkbox chk : ctrl.getChkRole()) {
            for (Role r : roleList) {
                if (chk.getLabel().equals(r.getName())) {
                    chk.setChecked(true);
                }
            }
        }
        ((Window) comp).doModal();
    }

    @Listen("onClick=#btnReset")
    public void doReset() throws UnknownHostException {
        UserService srv = Repository.getInstance().getUserService();
        UUID idOne = UUID.randomUUID();
        String str = idOne.toString().substring(0, 8);
        Properties props = System.getProperties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("test@lactien.com", "testtest");
            }
        });

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("test@lactien.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(user.getEmail()));
            message.setSubject("User Reset Password");
            String body = "<p>Dear " + user.getUsername() + ",</p>" + "<p>Your reset password is : " + str + "</p>";

            message.setContent(body, "text/html");
            Transport.send(message);
            user = srv.findByID(Long.parseLong(strId));
            Sha256Hash hash = new Sha256Hash(str, null, 1024);
            user.setPassword(hash.toBase64());
            srv.save(user);

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<Role> getRoleList() {
        return roleList;
    }

    public void setRoleList(List<Role> roleList) {
        this.roleList = roleList;
    }

}